package org.example.service;

import com.alipay.remoting.exception.CodecException;
import io.vertx.core.Vertx;
import io.vertx.mqtt.MqttServer;
import org.example.CommonMsg;
import org.example.order.MatchData;
import org.springframework.stereotype.Service;

@Service
public class MarketService {

    public MarketService() {
        System.out.println("start mqtt server.....");
        Vertx vertx = Vertx.vertx();
        MqttServer mqttServer = MqttServer.create(vertx);
        mqttServer.endpointHandler(endpoint -> {

            // shows main connect info
            System.out.println("MQTT client [" + endpoint.clientIdentifier() + "] request to connect, clean session = " + endpoint.isCleanSession());

            if (endpoint.auth() != null) {
                System.out.println("[username = " + endpoint.auth().getUsername() + ", password = " + endpoint.auth().getPassword() + "]");
            }
            System.out.println("[properties = " + endpoint.connectProperties() + "]");
            if (endpoint.will() != null) {
                System.out.println("[will topic = " + endpoint.will().getWillTopic() +
                        " QoS = " + endpoint.will().getWillQos() + " isRetain = " + endpoint.will().isWillRetain() + "]");
            }

            System.out.println("[keep alive timeout = " + endpoint.keepAliveTimeSeconds() + "]");

            // accept connection from the remote client
            endpoint.accept(false);
            endpoint.publishHandler(message -> {
               try {
                   CommonMsg commonMsg = CommonMsg.decodeFromBufferNoCsCheck(message.payload());
                   byte[] body = commonMsg.getBody();
                   MatchData data = MatchData.deserialize(body);
                   endpoint.publishAcknowledge(message.messageId());
                   System.out.println(data.toString());
               } catch (Exception e) {
                   System.out.println("receive msg, bug got error.");
                   e.printStackTrace();
               }

           });
        }).listen(1883, "127.0.0.1").onFailure(throwable -> System.out.println("error on start mqtt"));
    }
}
